<template>
  <div>
    <BreakSpace label="关爱信息" :containerStyle="{ marginBottom: '10px' }"/>
    <FormPanel
      ref="formPanel"
      :cols="4"
      :list="formList"
      formType="add"
      labelWidth="100"
      :isSubmitBtn="false"
      @formChange="formChangeHandle"
    />
    <div v-html="vhtml"></div>

    <div v-if="showSms">
      <BreakSpace label="短信发送" :containerStyle="{ marginBottom: '10px' }"/>
      <FormPanel
        ref="smsFormPanel"
        :cols="4"
        :list="smsFormList"
        formType="add"
        labelWidth="100"
        :isSubmitBtn="false"
      />
    </div>


    <div v-if="showHistory">
      <BreakSpace label="记录" :containerStyle="{ marginBottom: '10px' }"/>
      <div class="form-row">
        <el-row>
          <el-tabs type="border-card" v-model="activeName">
            <el-tab-pane label="关爱记录" name="careHistory"><careHistory :careTargetId="careTargetId" ref="careHistory"/></el-tab-pane>
            <el-tab-pane label="跟进记录" name="followHistory"><followHistory ref="followHistory"/></el-tab-pane>
          </el-tabs>
        </el-row>
      </div>
    </div>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">取 消</el-button>
      <el-button v-if="type !== 'show'" @click="saveDialog" type="primary">保存/发送</el-button>
    </div>
  </div>
</template>
<script>
import {
  getCareTaskListById,
  insertCustomerCare,
  birthdayAllCare,
  getBirthdayAllCareNum
} from '@/api/customerCare/saleVisit/potentialCustomerBirthday';
import { dictionary } from '@/utils/dictMixin';
import { formatdate } from '@/utils/index';
import careHistory from '../../tabs/careHistory.vue';
import followHistory from '../../tabs/followHistory.vue';

export default {
  name: 'newCarOnDayDetail',
  mixins: [dictionary],
  props: {
    type: String,
    selectedRows: Array,
    isShowHistory: Boolean,
    queryData: Object,
    careTargetId: String
  },
  components: {
    followHistory,
    careHistory
  },
  data(){
    return {
      formList: this.createFormList(),
      fetchAnswerParams: {},
      smsFormList: this.createSmsFormList(),
      activeName: 'careHistory',
      saveData: {},
      showSms: false,
      showHistory: false,
      employeeId: '',
      vhtml: ''
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      if(this.selectedRows.length>1){
        this.vhtml = "<div style='margin-left: 110px'>本次提醒为批量提醒，提醒条数是"+this.selectedRows.length+"！</div>";
      }else{
        if(!this.isShowHistory){
          getBirthdayAllCareNum(this.queryData).then(res=>{
            if(res.resultCode == 200){
              this.vhtml = "<div style='margin-left: 110px'>本次提醒为批量提醒，提醒条数是"+res.data+"！</div>";
            }else{
              this.$message.error('获取提醒条数失败!');
            }
          })
        }
      }
      if (this.type != 'add') {if(this.type == 'edit'){
          if(this.selectedRows.length==1){
            getCareTaskListById(this.selectedRows[0].careTargetId).then(res=>{
              if(res.resultCode == 200){
                if(res.data["nextCareDate"]&&res.data["nextCareDate"]!=""){
                  res.data["nextCareDate"] = formatdate(new Date(parseInt(res.data["nextCareDate"])),1);
                };
                if(res.data["careWay"]==15871002){
                  this.formList.find(item=>item.fieldName === 'careStatus').itemList = this.createDictList('1592')
                }
                this.formList.forEach(x => {
                  // if(x.fieldName === 'careName'){
                    x.initialValue = res.data[x.fieldName]
                  // }
                });
                //禁用关爱方式
                this.formList.find(item=>item.fieldName === 'careWay').disabled = true
                //关爱方式为短信时，关爱状态不可选
                if(res.data["careWay"]==15871002){
                  this.showSms = true;
                  this.formList.find(item=>item.fieldName==='careContent').hidden = true;
                  this.formList.find(item=>item.fieldName === 'careStatus').initialValue = this.createDictText(15921001, '1572')
                  this.formList.find(item=>item.fieldName === 'careStatus').disabled = true
                }else{
                  this.formList.find(item=>item.fieldName === 'careStatus').temList= [{text:"继续关爱",value:15921002},{text:"成功关爱",value:15921003},{text:"失败关爱",value:15921004}]
                  this.formList.find(item=>item.fieldName === 'careStatus').disabled = false
                }
                if(res.data["smsDaysAfterTask"]){
                  this.smsFormList.find(item=>item.fieldName === 'smsSendWay').initialValue = 15981001;
                  this.smsFormList.find(item=>item.fieldName === 'smsSendWay').disabled = false;
                }else{
                  this.smsFormList.find(item=>item.fieldName === 'smsSendWay').initialValue = 15981002;
                  this.smsFormList.find(item=>item.fieldName === 'smsSendWay').disabled = true;
                }
                this.smsFormList.find(item=>item.fieldName === 'mobilePhone').initialValue = res.data["mobilePhone"];
                this.smsFormList.find(item=>item.fieldName === 'smsDaysAfterTask').initialValue = res.data["smsDaysAfterTask"]+"天后发送";
                this.smsFormList.find(item=>item.fieldName === 'smsTemplateContent').initialValue = this.templateFormat(res.data["smsTemplateContent"]);
              }else{
                this.$message.error('获取关爱明细失败');
              }
            })
          }else{
            // debugger
            //关爱方式为短信时，关爱状态不可选
            if(this.selectedRows.length == 0 || this.selectedRows[0].careWay == 15871002){
              this.formList.find(item=>item.fieldName === 'careStatus').itemList = this.createDictList('1592')
              this.formList.find(item=>item.fieldName==='careContent').hidden = true;
              this.formList.find(item=>item.fieldName === 'careStatus').initialValue = 15921001
              this.formList.find(item=>item.fieldName === 'careStatus').disabled = true
            }else{
              this.formList.find(item=>item.fieldName === 'careStatus').temList= [{text:"继续关爱",value:15921002},{text:"成功关爱",value:15921003},{text:"失败关爱",value:15921004}]
              this.formList.find(item=>item.fieldName === 'careStatus').disabled = false
            }
            //禁用关爱方式
            this.formList.find(item=>item.fieldName === 'careWay').initialValue = this.selectedRows.length>0?this.selectedRows[0].careWay:15871002
            this.formList.find(item=>item.fieldName === 'careWay').disabled = true
          }
        }else{
          if(this.selectedRows.length==1){
            getCareTaskListById(this.selectedRows[0].careTargetId).then(res=>{
              if(res.resultCode == 200){
                if(res.data["nextCareDate"]&&res.data["nextCareDate"]!=""){
                  res.data["nextCareDate"] = formatdate(new Date(parseInt(res.data["nextCareDate"])),1);
                };
                if(res.data["careWay"]==15871002){
                  this.showSms = true;
                }
                this.formList.forEach(x => {
                  if(x.fieldName === 'careName'){
                    x.initialValue = res.data[x.fieldName]
                  }
                });
                if(res.data["smsDaysAfterTask"]){
                  this.smsFormList.find(item=>item.fieldName === 'smsSendWay').initialValue = 15981001;
                  this.smsFormList.find(item=>item.fieldName === 'smsSendWay').disabled = false;
                }else{
                  this.smsFormList.find(item=>item.fieldName === 'smsSendWay').initialValue = 15981002;
                  this.smsFormList.find(item=>item.fieldName === 'smsSendWay').disabled = true;
                }
                this.smsFormList.find(item=>item.fieldName === 'mobilePhone').initialValue = res.data["mobilePhone"];
                this.smsFormList.find(item=>item.fieldName === 'smsDaysAfterTask').initialValue = res.data["smsDaysAfterTask"]+"天后发送";
                this.smsFormList.find(item=>item.fieldName === 'smsTemplateContent').initialValue = this.templateFormat(res.data["smsTemplateContent"]);
              }else{
                this.$message.error('获取关爱明细失败');
              }
            })
          }
        }
      }
      this.showHistory = this.isShowHistory;
    },
    createFormList(){
      return [
        {
          type: 'INPUT',
          label: '关爱名称',
          fieldName: 'careName',
          disabled: true,
          initialValue: '新车当日关怀'
        },
        {
          type: 'SELECT',
          label: '关爱方式',
          fieldName: 'careWay',
          placeholder: '请选择',
          itemList: [{text:"短信",value:15871002},{text:"电话",value:15871003},{text:"邮件",value:15871004}],
          rules: [{ required: true, message: '请选择关爱方式', trigger: 'blur' }],
          change: val => {
            if(val == 15871002){
              this.showSms = true;
            }else{
              this.showSms = false;
            }
            if(val==15871002||val==15871004){
              this.formList.find(item=>item.fieldName==='careContent').initialValue = '';
              this.formList.find(item=>item.fieldName==='careContent').hidden = true;
              this.formList.find(item=>item.fieldName==='careContent').rules = []
            }else{
              this.formList.find(item=>item.fieldName==='careContent').rules = [{ required: true, message: '请输入关爱内容', trigger: 'blur' }]
              this.formList.find(item=>item.fieldName==='careContent').hidden = false;
            }
          }
        },
        {
          type: 'SELECT',
          label: '关爱状态',
          fieldName: 'careStatus',
          placeholder: '请选择',
          itemList: [{text:"继续关爱",value:15921002},{text:"成功关爱",value:15921003},{text:"失败关爱",value:15921004}],
          rules: [{ required: true, message: '请选择关爱状态', trigger: 'blur' }],
          change: val=>{
            if(val == 15921004){
              this.formList.find(item=>item.fieldName==='careFailureReason').disabled = false;
              this.formList.find(item=>item.fieldName==='careFailureReason').rules = [{ required: true, message: '请选择关爱失败原因', trigger: 'blur' }];
            }else{
              this.formList.find(item=>item.fieldName==='careFailureReason').disabled = true;
              this.formList.find(item=>item.fieldName==='careFailureReason').rules = [];
              this.formList.find(item=>item.fieldName==='careFailureReason').initialValue = "";
            }
            if(val == 15921002){
              this.formList.find(item=>item.fieldName==='nextCareDate').disabled = false;
              this.formList.find(item=>item.fieldName==='nextCareDate').rules = [{ required: true, message: '请选择下次关爱日期', trigger: 'blur' }];
            }else{
              this.formList.find(item=>item.fieldName==='nextCareDate').disabled = true;
              this.formList.find(item=>item.fieldName==='nextCareDate').rules = [];
              this.formList.find(item=>item.fieldName==='nextCareDate').initialValue = "";
            }
          }
        },
        {
          type: 'DATE',
          label: '下次关爱日期',
          fieldName: 'nextCareDate',
          dateType: 'exactdate',
          disabled: true,
          placeholder: '请选择',
          rules: [],
          minDateTime: formatdate(new Date(),1)
        },
        {
          type: 'SELECT',
          label: '失败原因',
          fieldName: 'careFailureReason',
          disabled: true,
          placeholder: '请选择',
          itemList: this.createDictList('1594'),
          rules: []
        },
        {
          type: 'TEXT_AREA',
          label: '关爱内容',
          selfCols: 4,
          fieldName: 'careContent',
          placeholder: '关爱内容',
          rules: [{ required: true, message: '请输入关爱内容', trigger: 'blur' }]
        },
        {
          type: 'TEXT_AREA',
          label: '客户反馈',
          selfCols: 4,
          fieldName: 'customerFeedback',
          placeholder: '客户反馈'
        }
      ]
    },
    templateFormat(template){
      if (template!=='') {
        var reg=new RegExp ("\\{\\[[^(\\s|\\})]+\\]\\}","g");
        var reg2=new RegExp ("[^\\{\\[\\]\\}]+","g");
        var matchResult= template.match(reg);
        if(!matchResult){
          return template;
        }
        var matchKeys;
        for(let i=0;i<matchResult.length;i++){
          var result= matchResult[i].match(reg2);
          var val = this.createDictText(result,result[0].substring(0,4));
          if(val||val==""){
            matchKeys=matchKeys==undefined?{}:matchKeys;
            matchKeys[result] = "{["+val+"]}";
          }
        }
        for (var key in matchKeys) {
          var reg3=new RegExp ("(\\{\\["+key+"\\]\\})","g");
          template = template.replace(reg3, matchKeys[key]);
        }
        return template;
      }else {
        return this;
      }
    },
    closeDialog(param) {
      this.$emit('close', false, param);
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    createSmsFormList(){
      return [
        {
          type: 'INPUT',
          label: '手机号',
          fieldName: 'mobilePhone',
          selfCols: 4,
          disabled: true,
          initialValue: ''
        },
        {
          type: 'RADIO',
          label: '发送方式',
          fieldName: 'smsSendWay',
          selfCols: 3,
          itemList: this.createDictList('1598'),
          initialValue: 15981001
        },
        {
          type: 'INPUT',
          label: '时间',
          fieldName: 'smsDaysAfterTask',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '发送短信内容',
          fieldName: 'smsTemplateContent',
          disabled: true,
          selfCols: 4
        }
      ]
    },
    saveDialog(){
      this.$refs.formPanel.SUBMIT_FORM();
      if(this.saveData&&this.saveData!=null){
        if(this.saveData.nextCareDate&&this.saveData.nextCareDate!=''){
          this.saveData.nextCareDate = this.saveData.nextCareDate+" 00:00:00";
        }
        let ids = "";
        this.selectedRows.forEach(row=>{
          ids += row.careTargetId+",";
        })
        this.saveData.customerFeedback = this.formList.find(item=>item.fieldName==='customerFeedback').initialValue;
        this.saveData.careTargetIdList = ids.substring(0,ids.length - 1);
        this.saveData.smsSendWay = this.smsFormList.find(item=>item.fieldName==='smsSendWay').initialValue
        this.saveData.careTypeCode = 15721009
        if(this.showHistory || this.selectedRows.length>0){
          insertCustomerCare(this.saveData).then(res=>{
            if(res.resultCode == 200){
              this.closeDialog('refresh');
            }else{
              this.$message.error('关爱失败');
            }
          })
        }else{
          let data = {
            ...this.saveData,
            ...this.queryData,
            careTypeCode:15721009
          }
          // console.log(data,"我是data呀")
          // return
          birthdayAllCare(data).then(res=>{
            if(res.resultCode == 200){
              this.closeDialog('refresh');
            }else{
              this.$message.error('全部关爱失败');
            }
          })
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.dialog-form {
  width: 100%;
  margin: 0;
}

.el-checkbox-group .el-checkbox + .el-checkbox {
  margin: 0;
}

.box {
  border: 1px solid @borderColor;
  border-radius: @borderRadius;
  box-shadow: @boxShadow;
  padding: @modulePadding;
  margin-top: 20px;
}
</style>
